/**
 * 
 */
$.fn.serializeObject = function()
{
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

$( document ).ready(function() {

	$(".cell1").click(function() {
		var id_res = this.id;
		window.location = '/elearning/lstcourses/course?idCor='+ id_res;
		return false;
	});
	$('#registerForm').submit(function(e){
		var $this = $(this);
		$.ajax({
			type: "POST",
			contentType : 'application/json',
			dataType : 'json',
			url: "/elearning/ajaxRegister",
			processData: false,
			data: JSON.stringify($this.serializeObject()),
			// data: JSON.stringify({toUser:"1",message:"chanvai"}), // Note it is important
			beforeSend: function() {  
				$('#registerForm .form-group').removeClass("has-error");
				$('#registerForm .checkbox').parent().removeClass("has-error");
			},
			success: function(data, textStatus) {
				if(data.error!=null){
					$.each(data.error,function(index,value){
						$('#registerForm input[name='+index+']').parent().addClass("has-error");
					})
					if(data.error.checkPrivacy!=null){
						$('#registerForm div.checkbox').parent().addClass("has-error");
					}
				}else{
					window.location.reload();
					history.go(0);
				}
			}
		});
		return false;
	});
	$('#LoginForm').submit(function(e){
		var $this = $(this);
		$.ajax({
			type: "POST",
			contentType : 'application/json',
			dataType : 'json',
			url: "/elearning/ajaxLogin",
			processData: false,
			data: JSON.stringify($this.serializeObject()),
			// data: JSON.stringify({toUser:"1",message:"chanvai"}), // Note it is important
			beforeSend: function() {  
				$('#LoginForm .form-group').removeClass("has-error");
			},
			success: function(data, textStatus) {
				if(data.error!=null){
					$.each(data.error,function(index,value){
						$('#LoginForm input[name='+index+']').parent().addClass("has-error");
					})
				}else{
					window.location.reload();
					history.go(0);
				}
			}
		});
		return false;
	});
	var total = $('.parallax__layer--back img').length;
	for(var i=0;i<total;i++){
		$($('.parallax__layer--back img')[i]).css({left:100*i+"vw"});
	}
	var height = $('.parallax').height();
	$('.parallax').scroll(function(){
		var currentScrollTop = $('.parallax').scrollTop();
		if ($('.parallax').scrollTop() >= height/3) {
			$('.header-fix').addClass('fixed-menu');	        
		}
		else {
			$('.header-fix').removeClass('fixed-menu');
			$('#blackOverlay').css('opacity',currentScrollTop*0.8/height);
		}

	});

	$(document).on('click','.btn-to-bottom',function(){
		var parallax = $('.parallax');
		parallax.animate({scrollTop:height}, '800', 'swing', function() { 
		});
	});
	$("#addques").click(function(e){
		e.preventDefault();
		var idt = $("#idT").val();
		$("#testid").val(idt);
		$('#add').modal() ;
	});
	//popover 1
	$('.request-friend').on('show.webui.popover', function () {
	});
	$('.request-friend').on('hidden.webui.popover', function () {
		if(!$('.webui-popover').is(':visible')){

		}
	});
	$('body').on('click', function () {
		setTimeout(function() {
			if(!$('.webui-popover').is(':visible')){
			}
		}, 1);

	});
	$(".request-friend").webuiPopover({placement:'bottom',title:'Yêu cầu kết bạn', type:'async', width: 400,cache:false,url:"/elearning/friendNotify", content:function(data){
		$('#friend-list .new,#friend-list .old').empty();
		if(data.friend!=null && data.friend.length>0){
			$.each(data.friend,function(key,value){
				if(!value.check){
					$('#friend-list .new').append('<li><a class="avartar" href="javascript:void(0)" data-content="'+value.fromName+'" data-id="'+value.fromUser+'"><img src="/elearning/resources/images/front/'+value.fromPic+'"/></a><button class="fb_btn_add_friend confirm-friend" type="button" data-id="'+value.fromUser+'"><i class="icon-add-friend"></i> Chấp Nhận</button><button class="fb_btn_add_friend ignore-friend" type="button" data-id="'+value.fromUser+'">Bỏ qua</button></li>');
				}else{
					$('#friend-list .old').append('<li><a class="avartar" href="javascript:void(0)" data-content="'+value.fromName+'" data-id="'+value.fromUser+'"><img src="/elearning/resources/images/front/'+value.fromPic+'"/></a><button class="fb_btn_add_friend confirm-friend" type="button" data-id="'+value.fromUser+'"><i class="icon-add-friend"></i> Chấp Nhận</button></li>');
				}
			});
			return $('#friend-list').parent().html();
		}else{
			return "Không có yêu cầu kết bạn nào";
		}

	}});
	//popover 2
	$('.messagenf').on('show.webui.popover', function () {	
	});
	$('.messagenf').on('hidden.webui.popover', function () {
		if(!$('.webui-popover').is(':visible')){
		}
	});
	$('body').on('click', function () {
		setTimeout(function() {
			if(!$('.webui-popover').is(':visible')){
			}
		}, 1);

	});
	$(".messagenf").webuiPopover({placement:'bottom',title:'Tin nhắn', type:'async', width: 400,cache:false,url:"/elearning/mesageNotify", content:function(data){
		$('#message-list ul').empty();
		if(data.message!=null && data.message.length>0){
			$.each(data.message,function(key,value){
				$('#message-list ul').append('<li data-id="'+value.fromUser+'"><a class="avartar" href="javascript:void(0)" data-content="'+value.fromName+'" data-id="'+value.fromUser+'"><img src="/elearning/resources/images/front/'+value.fromPic+'"/></a><div class="message-text">'+value.message+'</div></li>');
			});
			return $('#message-list').parent().html();
		}else{
			return "Không có tin nhắn nào";
		}

	}});
	$(".show-friend").click(function(){
		var index = $('.show-friend').index(this);
		var me = $(this);
		$.ajax({
			type: "POST",
			contentType : 'application/json',
			dataType : 'json',
			url: "/elearning/getAllUser",
			processData: false,
			data: '',
			success :function(result) {
				me.toggle();
				var html = '';
				result.forEach(function(entry) {
					html +='<li data-id="'+entry.id+'">'+entry.name+'</li>';
				});
				$(".friends").append(html);
				$($(".hide-friend")[index]).toggle();
				$(".friends li").click(function(){
					var me = $(this);
					var idx = -1;
					$.each($(".message-button"), function( index, value ) {
						if($($(".message-button")[index]).data("id") == me.data("id")){
							idx = index;
							return false;
						}
					});
					if(idx == -1){
						var copy = $("#tab-friend").clone();
						$(".friendList-bot").append(copy);
						var lenght = $("#tab-friend .message-button").length;
						$($("#tab-friend .message-button")[lenght-2]).data("id",me.data("id"));
					}
				});
			}
		});
	});
	$(document).on('click','#message-list ul li',function(){
		if($(".messagenf span").data("content")>0){
			$(".messagenf span").data("content",$(".messagenf span").data("content")-1);
		}
		if($(".messagenf span").data("content")<1){
			$(".messagenf span").remove();
		}
		var me = $(this);
		var idx = -1;
		//get recent message or unread message
		$.each($(".message-button"), function( index, value ) {
			if($($(".message-button")[index]).data("id") == me.data("id")){
				idx = index;
				return false;
			}
		});
		if(idx == -1){
			var copy = $("#tab-friend").clone();
			$.ajax({
				type: "POST",
				contentType : 'application/json',
				dataType : 'json',
				url: "/elearning/getAllMessage",
				processData: false,
				data: JSON.stringify({idFriend:me.data("id")}),
				success :function(result) {
					$.each(result.message.reverse(), function( index, value ) {
						if(value.me == value.toUser){
							copy.find(".logchat").append("<li>"+value.fromName+":"+ value.message +"</li>");
						}else{
							copy.find(".logchat").append("<li>me:"+ value.message +"</li>");
						}
					});
				}
			});
			$(".friendList-bot").append(copy);
			var lenght = $("#tab-friend .message-button").length;
			$($("#tab-friend .message-button")[lenght-2]).data("id",me.data("id"));
		}
	});
	$(document).on('click','#message-list ul a',function(e){
		e.stopPropagation();
	});
	$(".hide-friend").click(function(){
		var index = $('.hide-friend').index(this);
		$(this).toggle();
		$($(".show-friend")[index]).toggle();
		$(".friends").empty();
	});
	$(document).on('click','.ignore-friend',function(){
		var idFriend = $(this).data("id");
		$.ajax({
			type: "POST",
			contentType : 'application/json',
			dataType : 'json',
			url: "/elearning/hasCheck",
			processData: false,
			data: JSON.stringify({idFriend:idFriend}),
			// data: JSON.stringify({toUser:"1",message:"chanvai"}), // Note it is important
			success :function(result) {
				// do what ever you want with data
			}
		});
		var copy = $(this).parent().clone();
		$(this).parent().animate({ "opacity": "0.2"}, "fast", "linear",function(){$(this).remove()} );
		$(".old").prepend(copy).fadeIn('slow');
		$(".old li .ignore-friend").remove();
		if($(".request-friend span").data("content")>0){
			$(".request-friend span").data("content",$(".request-friend span").data("content")-1);
		}
		if($(".request-friend span").data("content")<1){
			$(".request-friend span").remove();
		}
	});
	$(document).on('click','.confirm-friend',function(){
		var idFriend = $(this).data("id");
		$.ajax({
			type: "POST",
			contentType : 'application/json',
			dataType : 'json',
			url: "/elearning/confirm",
			processData: false,
			data: JSON.stringify({idFriend:idFriend}),
			// data: JSON.stringify({toUser:"1",message:"chanvai"}), // Note it is important
			success :function(result) {

			}
		});
		var copy = $(this).parent().clone();
		$(this).parent().animate({ "opacity": "0.2"}, "fast", "linear",function(){$(this).remove()} );
		if($(".request-friend span").data("content")>0){
			$(".request-friend span").data("content",$(".request-friend span").data("content")-1);
		}
		if($(".request-friend span").data("content")<1){
			$(".request-friend span").remove();
		}
	});
	$(document).on('click', '.message-button' ,function() {
		var toUser = $(this).data("id");
		var index = $(".message-button").index(this);
		if($($(".message-input")[index]).val()!=null && $($(".message-input")[index]).val().trim()!=''){
			$($(".logchat")[index]).append("<li>me:"+ $($(".message-input")[index]).val() +"</li>");
			$.ajax({
				type: "POST",
				contentType : 'application/json',
				dataType : 'json',
				url: "/elearning/sendMessage",
				processData: false,
				data: JSON.stringify({toUser:toUser,message:$($(".message-input")[index]).val()}),
				// data: JSON.stringify({toUser:"1",message:"chanvai"}), // Note it is important
				success :function(result) {
					// do what ever you want with data
				}
			});
		}
	});
	$(document).on('click', '.close' ,function() {
		var index = Math.floor($('.close').index(this)/2);
		$($(".wrap-content")[index]).remove();
	});

	$(document).on('click', '.addFriend' ,function() {
		var toUser = $(this).data("id");
		$(".addFriend").html('<i class="icon-add-friend"></i>Đã gửi lời mời kết bạn');
		$(".addFriend").removeClass("addFriend");
		$.ajax({
			type: "POST",
			contentType : 'application/json',
			dataType : 'json',
			url: "/elearning/addFriend",
			processData: false,
			data: JSON.stringify({toUser:toUser}),
			// data: JSON.stringify({toUser:"1",message:"chanvai"}), // Note it is important
			complete: function(response, textStatus) {  
			},
			success: function(data, textStatus) {
				if(data.success==true){

				}
			}
		});
	});

	$.each($(".menu"),function(key,value){
		$.each($(".menu li"),function(key1,value1){
			if($(value).data("path") == $(value1).data("path")){
				$(value1).addClass("highlight-path");
			}
		});
	});
	$(document).on('click', '.btn-next' ,function() {
		var total = $('.parallax__layer--back img').length;
		$('.btn-slide').data('index',($('.btn-slide').data('index')+1)%total);
		$('.parallax__layer--back').css({left:-$('.btn-slide').data('index')*150+"vw"}); 
	});
	$(document).on('click', '.btn-pre' ,function() {
		var total = $('.parallax__layer--back img').length;
		$('.btn-slide').data('index',($('.btn-slide').data('index')+total-1)%total);
		$('.parallax__layer--back').css({left:-$('.btn-slide').data('index')*150+"vw"}); 
	});
});